
from django.core.cache import cache

from .Const import CONST

class RedisUtils(object):

    def set(self,key,value):
        # 存储数据到 Redis # timeout 是缓存过期时间，单位为秒 一个小时后期
        cache.set(key, value, timeout=60*60)

    def get(self,key):
        return cache.get(key)

    def generate_toekn(self,key,value):
        key = CONST.TOKEN_KEY+key
        cache.set(key, value, timeout=60 * 60)
        return key

    def delete_toekn(self, key):
        cache.delete(key)
    def gettoekn(self,key):
        return cache.get(key)

    def isLogin(self,request):
        auth_header = request.META.get('HTTP_AUTHORIZATION', '')
        if auth_header.startswith('Token '):
            token = auth_header.split(' ')[1]  # 提取 Token
            return cache.get(token) is None
        # 从 Redis 获取数据
        return False

    def isAdminLogin(self,request):
        auth_header = request.headers.get('Authorization', '')
        auth_header = auth_header.split('Bearer ')[-1] if auth_header.startswith('Bearer ') else None
        if auth_header.startswith('Token '):
            token = auth_header.split(' ')[1]  # 提取 Token
            return cache.get(token) is None and cache.get(token) == 'admin'
        # 从 Redis 获取数据
        return False


redis_util = RedisUtils()